package com.tanhua.server.service;

import com.tanhua.autocofig.template.HuanXinTemplate;
import com.tanhua.autocofig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.Exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    private static final String prefix = "CHECK_CODE_";

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //发送验证码
    public void sendMsg(String phone) {
        //随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //发送短信
        //smsTemplate.sendMessage(phone, code);
        //将验证码存入redis
        redisTemplate.opsForValue().set(prefix + phone, code, Duration.ofMinutes(5));
    }

    //验证登录
    public Map loginVerification(String phone, String code) {
        //从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(prefix + phone);
        //对验证码进行校验
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除redis中的验证码
        redisTemplate.delete(prefix + phone);
        //通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        Boolean isNew = false;
        //如果用户不存在则创建用户
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册换新用户
            String hxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create){
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        //通过JWT生成token(存入ID和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }
}
